package com.zbkj.service.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.zbkj.common.constants.AgentConstants;
import com.zbkj.common.enums.RoleEnum;
import com.zbkj.common.model.admin.SystemAdmin;
import com.zbkj.common.model.agent.*;
import com.zbkj.common.model.article.Article;
import com.zbkj.common.page.CommonPage;
import com.zbkj.common.request.*;
import com.github.pagehelper.PageHelper;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zbkj.common.exception.AppException;
import com.zbkj.common.response.*;

import com.zbkj.common.result.CommonResultCode;
import com.zbkj.common.utils.SecurityUtil;
import com.zbkj.common.vo.LoginUserVo;
import com.zbkj.service.dao.BrandAgentConfigDao;
import com.zbkj.service.service.*;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zbkj.service.util.BrandUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author dazongzi
* @description BrandAgentConfigServiceImpl 接口实现
* @date 2025-07-01
*/
@Service
public class BrandAgentServiceImpl extends ServiceImpl<BrandAgentConfigDao, BrandAgent> implements BrandAgentService {

    @Resource
    private BrandAgentConfigDao dao;

    @Autowired
    private BrandAgentItemsService brandAgentItemsService;

    @Autowired
    private BrandAgentRegionService brandAgentRegionService;

    @Autowired
    private AgentCategoryService agentCategoryService;

    @Autowired
    private TransactionTemplate transactionTemplate;

    @Autowired
    private AgentConfigService agentConfigService;

    @Autowired
    private SystemAdminService systemAdminService;

    @Autowired
    private UserAgentService userAgentService;
    @Autowired
    private BrandService brandService;


    @Override
    public Boolean create(BrandAgentSaveRequest request) {
        LoginUserVo loginUserVo = SecurityUtil.getLoginUserVo();
        checkSaveRequest(request, loginUserVo.getUser().getId());
        BrandAgent brandAgent = new BrandAgent();
        BeanUtils.copyProperties(request, brandAgent, "id");
        Integer brandId = BrandUtil.getBrandIdByUrl();
        brandAgent.setBrandId(brandId);
        brandAgent.setType(0);
        if (loginUserVo.getUser().getType().equals(RoleEnum.BRAND_AGENT.getValue())){
            brandAgent.setType(1);
        }
        brandAgent.setSystemAdminId(loginUserVo.getUser().getId());
        // 拼接地址
        brandAgent.setRegion(this.getRegion(request));
        // 检查权限
        checkAdd(request, loginUserVo.getUser().getId());
        if (CollUtil.isNotEmpty(request.getRegionList())) {
            brandAgent.setRegionType(request.getRegionList().get(0).getRegionType());
        }
        // 社区/村
        if (StrUtil.isNotBlank(request.getTribe())) {
            brandAgent.setRegionType(AgentConstants.AGENT_LEVEL_5);
        }
        // 小区
        if (StrUtil.isNotBlank(request.getCommunity())) {
            brandAgent.setRegionType(AgentConstants.AGENT_LEVEL_6);
        }
        boolean save = save(brandAgent);
        if (!save) {
            throw new AppException(CommonResultCode.VALIDATE_FAILED, "添加失败");
        }
        return addAgentRegionAndItem(request, brandAgent.getId(), brandId);
    }

    private String getRegion(BrandAgentSaveRequest request) {
        if (CollUtil.isEmpty(request.getRegionList())) {
            return "";
        }
        List<String> regionNameList = new ArrayList<>();
        BrandAgentItemSaveRequest brandAgentItemSaveRequest = request.getRegionList().get(0);
        if (StrUtil.isNotBlank(brandAgentItemSaveRequest.getProvince())) {
            regionNameList.add(brandAgentItemSaveRequest.getProvince());
        }
        if (StrUtil.isNotBlank(brandAgentItemSaveRequest.getCity())) {
            regionNameList.add(brandAgentItemSaveRequest.getCity());
        }
        if (StrUtil.isNotBlank(brandAgentItemSaveRequest.getDistrict())) {
            regionNameList.add(brandAgentItemSaveRequest.getDistrict());
        }
        if (StrUtil.isNotBlank(brandAgentItemSaveRequest.getStreet())) {
            regionNameList.add(brandAgentItemSaveRequest.getStreet());
        }
        if (StrUtil.isNotBlank(request.getTribe())) {
            regionNameList.add(request.getTribe());
        }
        if (StrUtil.isNotBlank(request.getCommunity())) {
            regionNameList.add(request.getCommunity());
        }
        return CollUtil.join(regionNameList, "/");
    }

    private void checkSaveRequest(BrandAgentSaveRequest request, Integer adminId) {
        LambdaQueryWrapper<BrandAgent> checkWrapper = new LambdaQueryWrapper<>();
        checkWrapper.eq(BrandAgent::getBrandId, BrandUtil.getBrandIdByUrl());
        checkWrapper.eq(BrandAgent::getIsDel, 0);
        checkWrapper.eq(BrandAgent::getSystemAdminId, adminId);
        checkWrapper.eq(BrandAgent::getTitle, request.getTitle().trim());
        long count = count(checkWrapper);
        if (count > 0) {
            throw new AppException("标题已存在");
        }
    }

    /**
     * 分页查询品牌商代理设置表
     *
     * @param request          请求参数
     * @param pageParamRequest 分页类参数
     * @return List<BrandAgentConfig>
     * @author dazongzi
     * @since 2025-07-01
     */
    @Override
    public PageInfo<BrandAgentPageDataResponse> getPageList(BrandAgentSearchRequest request, PageParamRequest pageParamRequest) {
        SystemAdmin currentUser = SecurityUtil.getLoginUserVo().getUser();

        Page<Article> articlePage = PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());

        //带 BrandAgentConfig 类的多条件查询
        LambdaQueryWrapper<BrandAgent> lambdaQueryWrapper = Wrappers.lambdaQuery();

        if (ObjectUtil.isNotEmpty(request.getTitle())) {
            lambdaQueryWrapper.like(BrandAgent::getTitle, URLUtil.decode(request.getTitle()));
        }
        lambdaQueryWrapper.eq(BrandAgent::getIsDel, false);
        lambdaQueryWrapper.eq(BrandAgent::getSystemAdminId, currentUser.getId());
        lambdaQueryWrapper.eq(BrandAgent::getBrandId, BrandUtil.getBrandIdByUrl());
        lambdaQueryWrapper.orderByDesc(BrandAgent::getCreateTime);
        List<BrandAgent> brandAgents = dao.selectList(lambdaQueryWrapper);
        List<BrandAgentPageDataResponse> list = new ArrayList<>();

        brandAgents.stream().forEach(x->{
            BrandAgentPageDataResponse brandAgentConfigResponse = new BrandAgentPageDataResponse();
            BeanUtils.copyProperties(x, brandAgentConfigResponse);
            if (x.getType().equals(1)) {
                SystemAdmin agentInfo = systemAdminService.getAgentInfo(x.getSystemAdminId());
                if (ObjectUtil.isNotNull(agentInfo)) {
                    brandAgentConfigResponse.setAgentUserName(agentInfo.getRealName());
                } else {
                    brandAgentConfigResponse.setAgentUserName("无");
                }
            }
            BrandAgentRegion brandAgentRegion = brandAgentRegionService.getCommunity(x.getId());
            if (ObjectUtil.isNotNull(brandAgentRegion)) {
                brandAgentConfigResponse.setRegionId(brandAgentRegion.getId());
                // 小区
                if (brandAgentConfigResponse.getRegionType().equals(AgentConstants.AGENT_LEVEL_6)) {
                    // 小区名称和区域ID
                    brandAgentConfigResponse.setCommunity(brandAgentRegion.getCommunity());
                }
            }
            list.add(brandAgentConfigResponse);
        });
        return CommonPage.copyPageInfo(articlePage, list);
    }

    @Override
    public PageInfo<PlatformBrandAgentPageDataResponse> getPageListPlatform(BrandAgentSearchRequest request, PageParamRequest pageParamRequest) {
        Page<Article> articlePage = PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());

        //带 BrandAgentConfig 类的多条件查询
        LambdaQueryWrapper<BrandAgent> lambdaQueryWrapper = Wrappers.lambdaQuery();

        if (ObjectUtil.isNotEmpty(request.getTitle())) {
            lambdaQueryWrapper.like(BrandAgent::getTitle, URLUtil.decode(request.getTitle()));
        }
        if (request.getBrandId() != null && request.getBrandId() > 0) {
            SystemAdmin systemAdminTmp = systemAdminService.getById(request.getBrandId());
            lambdaQueryWrapper.eq(BrandAgent::getBrandId, systemAdminTmp.getId());
        }
        lambdaQueryWrapper.eq(BrandAgent::getIsDel, false);
        lambdaQueryWrapper.orderByDesc(BrandAgent::getCreateTime);
        List<BrandAgent> brandAgents = dao.selectList(lambdaQueryWrapper);
        List<PlatformBrandAgentPageDataResponse> list = new ArrayList<>();

        brandAgents.stream().forEach(x->{
            PlatformBrandAgentPageDataResponse brandAgentConfigResponse = new PlatformBrandAgentPageDataResponse();
            BeanUtils.copyProperties(x, brandAgentConfigResponse);
            SystemAdmin agentInfo = systemAdminService.getAgentInfo(x.getSystemAdminId());
            if (ObjectUtil.isNotNull(agentInfo)) {
                brandAgentConfigResponse.setCreateBy(agentInfo.getRealName());
            }
            BrandAgentRegion brandAgentRegion = brandAgentRegionService.getCommunity(x.getId());
            if (ObjectUtil.isNotNull(brandAgentRegion)) {
                // 小区
                if (brandAgentConfigResponse.getRegionType().equals(AgentConstants.AGENT_LEVEL_6)) {
                    // 小区名称和区域ID
                    brandAgentConfigResponse.setCommunity(brandAgentRegion.getCommunity());
                }
            }
            Integer brandIdById = systemAdminService.getBrandIdById(x.getBrandId());
            brandAgentConfigResponse.setBrandName(brandService.getNameById(brandIdById));
            list.add(brandAgentConfigResponse);
        });
        return CommonPage.copyPageInfo(articlePage, list);
    }

    @Override
    public BrandAgentDetailResponse getDetailById(Integer id) {
        BrandAgent brandAgent = getByIdException(id);
        BrandAgentDetailResponse brandAgentConfigResponse = new BrandAgentDetailResponse();
        BeanUtils.copyProperties(brandAgent, brandAgentConfigResponse);
        // 区域
        List<BrandAgentRegion> brandAgentRegionList = brandAgentRegionService.getListByBrandAgentId(id);
        if (CollUtil.isNotEmpty(brandAgentRegionList)) {
            List<BrandAgentRegionResponse> brandAgentItemResponseList = new ArrayList<>();
            brandAgentRegionList.stream().forEach(region -> {
                BrandAgentRegionResponse brandAgentRegionResponse = new BrandAgentRegionResponse();
                BeanUtils.copyProperties(region, brandAgentRegionResponse);
                // 已设置的分类
                List<BrandAgentItems> brandAgentItemsList = brandAgentItemsService.getListByRegionId(region.getId());
                // 全部分类
                List<BrandAgentCategoryListResponse> platformCategotyList = agentConfigService.getPlatformCategoryList();
                if (CollUtil.isNotEmpty(platformCategotyList)) {
                    List<BrandAgentCategoryResponse> brandAgentItemsResponses = new ArrayList<>();
                    for (BrandAgentCategoryListResponse brandAgentCategoryListResponse : platformCategotyList) {
                        BrandAgentCategoryResponse brandAgentItemsResponse = new BrandAgentCategoryResponse();
                        brandAgentItemsResponse.setBrokerage(BigDecimal.ZERO);
                        BeanUtils.copyProperties(brandAgentCategoryListResponse, brandAgentItemsResponse);
                        brandAgentItemsResponse.setIsSelected(false);
                        // 勾选
                        setIsSelected(brandAgentItemsResponse, brandAgentItemsList);
                        brandAgentItemsResponses.add(brandAgentItemsResponse);
                    }
                    brandAgentRegionResponse.setItemList(brandAgentItemsResponses);
                }
                if (region.getRegionType().equals(AgentConstants.AGENT_LEVEL_5) || region.getRegionType() > AgentConstants.AGENT_LEVEL_5) {
                    // 因为列表只有1个所以这里直接赋值
                    brandAgentConfigResponse.setTribe(region.getTribe());
                }
                if (region.getRegionType().equals(AgentConstants.AGENT_LEVEL_6)) {
                    // 因为列表只有1个所以这里直接赋值
                    brandAgentConfigResponse.setCommunity(region.getRegionName());
                }
                brandAgentItemResponseList.add(brandAgentRegionResponse);
            });
            brandAgentConfigResponse.setRegionList(brandAgentItemResponseList);
        }
        return brandAgentConfigResponse;
    }

    private void setIsSelected(BrandAgentCategoryResponse response, List<BrandAgentItems> brandAgentItemsList) {
        if (CollUtil.isNotEmpty(brandAgentItemsList)) {
            List<BrandAgentItems> collect = brandAgentItemsList.stream().filter(item -> item.getCategoryId().equals(response.getCategoryId())).collect(Collectors.toList());
            if (CollUtil.isNotEmpty(collect)) {
                response.setIsSelected(true);
                response.setBrokerage(collect.get(0).getBrokerage());
            }
        }
    }

    public BrandAgentDetailResponse getDetailByIdOld(Integer id) {
        BrandAgent brandAgent = getByIdException(id);
        BrandAgentDetailResponse brandAgentConfigResponse = new BrandAgentDetailResponse();
        BeanUtils.copyProperties(brandAgent, brandAgentConfigResponse);
        // 区域
        List<BrandAgentRegion> brandAgentRegionList = brandAgentRegionService.getListByBrandAgentId(id);
        if (CollUtil.isNotEmpty(brandAgentRegionList)) {
            List<BrandAgentRegionResponse> brandAgentItemResponseList = new ArrayList<>();
            brandAgentRegionList.stream().forEach(x -> {
                BrandAgentRegionResponse brandAgentRegionResponse = new BrandAgentRegionResponse();
                BeanUtils.copyProperties(x, brandAgentRegionResponse);
                // 分类
                List<BrandAgentItems> listByRegionId = brandAgentItemsService.getListByRegionId(x.getId());
                if (CollUtil.isNotEmpty(listByRegionId)) {
                    List<BrandAgentCategoryResponse> brandAgentItemsResponses = new ArrayList<>();
                    listByRegionId.stream().forEach(y -> {
                        BrandAgentCategoryResponse brandAgentItemsResponse = new BrandAgentCategoryResponse();
                        BeanUtils.copyProperties(y, brandAgentItemsResponse);
                        brandAgentItemsResponse.setIsSelected(true);
                        brandAgentItemsResponses.add(brandAgentItemsResponse);
                    });
                    brandAgentRegionResponse.setItemList(brandAgentItemsResponses);
                }
                brandAgentItemResponseList.add(brandAgentRegionResponse);
            });
            brandAgentConfigResponse.setRegionList(brandAgentItemResponseList);
        }
        return brandAgentConfigResponse;
    }

    @Override
    public boolean updateBrand(BrandAgentSaveRequest request) {
        checkUpdateRequest(request);
        BrandAgent brandAgent = new BrandAgent();
        BeanUtils.copyProperties(request, brandAgent);
        brandAgent.setId(request.getId());
        brandAgent.setRegion(getRegion(request));
        // 检查权限
        LoginUserVo loginUserVo = SecurityUtil.getLoginUserVo();
        checkAdd(request, loginUserVo.getUser().getId());
        // 社区/村
        if (StrUtil.isNotBlank(request.getTribe())) {
            brandAgent.setRegionType(AgentConstants.AGENT_LEVEL_5);
        }
        // 小区
        if (StrUtil.isNotBlank(request.getCommunity())) {
            brandAgent.setRegionType(AgentConstants.AGENT_LEVEL_6);
        }
        updateById(brandAgent);
        // 分类数据
        List<BrandAgentRegion> crowdProjectItemsList = brandAgentRegionService.getListByBrandAgentId(brandAgent.getId());
        if (CollUtil.isNotEmpty(crowdProjectItemsList)) {
            List<Integer> oldIds = crowdProjectItemsList.stream().map(BrandAgentRegion::getId).distinct().collect(Collectors.toList());
            brandAgentItemsService.deleteByRegionId(oldIds);

            List<Integer> newIds = request.getRegionList().stream().map(BrandAgentItemSaveRequest::getId).distinct().collect(Collectors.toList());
            if (CollUtil.isNotEmpty(newIds)) {
                // 已删除的id 计算差集，找出在 list1 中但不在 list2 中的元素
                Collection<Integer> delIds = CollUtil.disjunction(oldIds, newIds);
                if (CollUtil.isNotEmpty(delIds)) {
                    brandAgentRegionService.removeByIds(delIds);
                }
            }
        }
        // 添加地区
        Integer brandId = BrandUtil.getBrandIdByUrl();
        List<BrandAgentItemSaveRequest> regionList = request.getRegionList();
        if (CollUtil.isNotEmpty(regionList)) {
            BrandAgentItemSaveRequest regionObj = regionList.get(0);

            BrandAgentRegion brandAgentRegion = brandAgentRegionService.getById(regionObj.getId());
            if(ObjectUtil.isNull(brandAgentRegion)){
                brandAgentRegion = new BrandAgentRegion();
                brandAgentRegion.setBrandAgentId(brandAgent.getId());
                brandAgentRegion.setBrandId(brandId);
            }
            BeanUtils.copyProperties(regionObj, brandAgentRegion);
            // 社区/村
            if (StrUtil.isNotBlank(request.getTribe())) {
                brandAgentRegion.setRegionId("");
                brandAgentRegion.setRegionType(AgentConstants.AGENT_LEVEL_5);
                brandAgentRegion.setRegionName(request.getTribe());
                brandAgentRegion.setTribe(request.getTribe());
            }
            // 小区
            if (StrUtil.isNotBlank(request.getCommunity())) {
                brandAgentRegion.setRegionId("");
                brandAgentRegion.setRegionType(AgentConstants.AGENT_LEVEL_6);
                brandAgentRegion.setRegionName(request.getCommunity());
                brandAgentRegion.setCommunity(request.getCommunity());
            }
            brandAgentRegionService.saveOrUpdate(brandAgentRegion);
            // 分类分成设置
            List<BrandAgentCategoryRequest> categoryList = regionObj.getItemList();
            if (CollUtil.isNotEmpty(categoryList)) {
                List<BrandAgentItems> brandAgentItemsList = new ArrayList<>();
                for (BrandAgentCategoryRequest category : categoryList) {
                    if (BooleanUtil.isTrue(category.getIsSelected())) {
                        BrandAgentItems brandAgentItems = new BrandAgentItems();
                        BeanUtils.copyProperties(category, brandAgentItems);
                        brandAgentItems.setAgentReginId(brandAgentRegion.getId());
                        AgentCategory agentCategory = agentCategoryService.getById(category.getCategoryId());
                        brandAgentItems.setCategorySn(agentCategory.getCategorySn());
                        brandAgentItems.setCategoryName(agentCategory.getCategoryName());
                        brandAgentItems.setStatus(1);
                        brandAgentItems.setBrandId(brandId);
                        brandAgentItemsList.add(brandAgentItems);
                    }
                }
                brandAgentItemsService.saveBatch(brandAgentItemsList);
            }
        }
        return true;
    }

    private void checkUpdateRequest(BrandAgentSaveRequest request) {
        if (ObjectUtil.isNull(request.getId())) {
            throw new AppException("ID不能为空");
        }
    }

    @Override
    public boolean batchDelete(List<Integer> idList) {
        LambdaUpdateWrapper<BrandAgent> wrapper = new LambdaUpdateWrapper<>();
        wrapper.set(BrandAgent::getIsDel, 1);
        wrapper.in(BrandAgent::getId, idList);
        return transactionTemplate.execute(e -> {
            update(wrapper);
            for (Integer id : idList) {
                // 分类数据
                List<BrandAgentRegion> list = brandAgentRegionService.getListByBrandAgentId(id);
                if (CollUtil.isNotEmpty(list)) {
                    List<Integer> auditIdList = list.stream().map(BrandAgentRegion::getId).distinct().collect(Collectors.toList());
                    brandAgentItemsService.deleteByRegionId(auditIdList);
                    brandAgentRegionService.deleteByConfigId(Arrays.asList(id));
                }
            }
            return Boolean.TRUE;
        });
    }

    @Override
    public boolean updateStatus(BrandAgentStatusRequest request) {
        BrandAgent brandAgent = getById(request.getId());
        if (ObjectUtil.isNull(brandAgent)) {
            throw new AppException("品牌商代理设置不存在");
        }
        if (!brandAgent.getBrandId().equals(BrandUtil.getBrandIdByUrl())) {
            throw new AppException("暂无权限修改");
        }
        if (brandAgent.getStatus().equals(request.getStatus())) {
            return true;
        }
        brandAgent.setStatus(request.getStatus());
        return updateById(brandAgent);
    }

    @Override
    public AgentUserRegionResponse getBrandRegionList(Integer brandId) {
//        LambdaQueryWrapper<BrandAgentRegion> lqw = Wrappers.lambdaQuery();
//        lqw.eq(BrandAgentRegion::getBrandAgentId, true);
//        return dao.selectList(lqw);
//
        return null;
    }

    private Boolean addAgentRegionAndItem(BrandAgentSaveRequest request, Integer id, Integer brandId) {
        // 添加地区
        List<BrandAgentItemSaveRequest> regionList = request.getRegionList();
        if (CollUtil.isNotEmpty(regionList)) {
            BrandAgentItemSaveRequest regionObj = regionList.get(0);
            BrandAgentRegion brandAgentRegion = new BrandAgentRegion();
            BeanUtils.copyProperties(regionObj, brandAgentRegion);
            brandAgentRegion.setBrandAgentId(id);
            brandAgentRegion.setBrandId(brandId);
            // 社区/村
            if (StrUtil.isNotBlank(request.getTribe())) {
                brandAgentRegion.setRegionId("");
                brandAgentRegion.setRegionType(AgentConstants.AGENT_LEVEL_5);
                brandAgentRegion.setRegionName(request.getTribe());
                brandAgentRegion.setTribe(request.getTribe());
            }
            // 小区
            if (StrUtil.isNotBlank(request.getCommunity())) {
                brandAgentRegion.setRegionId("");
                brandAgentRegion.setRegionType(AgentConstants.AGENT_LEVEL_6);
                brandAgentRegion.setRegionName(request.getCommunity());
                brandAgentRegion.setCommunity(request.getCommunity());
            }
            brandAgentRegionService.save(brandAgentRegion);
            // 分类分成设置
            List<BrandAgentCategoryRequest> categoryList = regionObj.getItemList();
            if (CollUtil.isNotEmpty(categoryList)) {
                List<BrandAgentItems> brandAgentItemsList = new ArrayList<>();
                for (BrandAgentCategoryRequest category : categoryList) {
                    if (BooleanUtil.isTrue(category.getIsSelected())) {
                        BrandAgentItems brandAgentItems = new BrandAgentItems();
                        BeanUtils.copyProperties(category, brandAgentItems);
                        brandAgentItems.setAgentReginId(brandAgentRegion.getId());
                        AgentCategory agentCategory = agentCategoryService.getById(category.getCategoryId());
                        brandAgentItems.setCategorySn(agentCategory.getCategorySn());
                        brandAgentItems.setCategoryName(agentCategory.getCategoryName());
                        brandAgentItems.setStatus(1);
                        brandAgentItems.setBrandId(brandId);
                        brandAgentItemsList.add(brandAgentItems);
                    }
                }
                brandAgentItemsService.saveBatch(brandAgentItemsList);
            }
        }
        return true;
    }

    private BrandAgent getByIdException(Integer jobId) {
        BrandAgent scheduleJob = getById(jobId);
        if (ObjectUtil.isNull(scheduleJob) || BooleanUtil.isTrue(scheduleJob.getIsDel())) {
            throw new AppException("品牌商代理设置不存在");
        }
        return scheduleJob;
    }

    /**
     * 检查权限
     * @param request
     * @param adminId
     */
    private void checkAdd(BrandAgentSaveRequest request, Integer adminId) {
        List<String> cityNameList = getCityList(request.getRegionList(), request.getCommunity(), request.getTribe());

        List<SystemAdminAgentCityResponse> nameList = userAgentService.getCityListByUserId(adminId);
        if (CollUtil.isNotEmpty(nameList)) {
            List<String> oldCityNameList = nameList.stream().map(SystemAdminAgentCityResponse::getCity).distinct().collect(Collectors.toList());
            int i = 0;
            for (SystemAdminAgentCityResponse response : nameList) {
                for (String name : cityNameList) {
                    if (name.equals(response.getCity())) {
                        throw new AppException("不能添加该地区");
                    }
                    if (name.startsWith(response.getCity())) {
                        i++;
                    }
                }
            }
            if (i != cityNameList.size()) {
                throw new AppException("必须选择代理人所属区域下方的地区");
            }
            int matchCount = 0;
            for (String name : cityNameList) {
                if (inList(name, oldCityNameList)) {
                    matchCount++;
                }
            }
            if (matchCount != cityNameList.size()) {
                throw new AppException("不能添加其他地区");
            }

        }
    }

    private boolean inList(String name, List<String> oldCityNameList) {
        for (String s : oldCityNameList) {
            if(name.contains(s)){
                return true;
            }
        }
        return false;
    }

    private List<String> getCityList(List<BrandAgentItemSaveRequest> regionList, String community, String tribe) {
        List<String> list = new ArrayList<>();
        for (BrandAgentItemSaveRequest brandAgentItemSaveRequest : regionList) {
            List<String> regionNameList = new ArrayList<>();
            if (StrUtil.isNotBlank(brandAgentItemSaveRequest.getProvince())) {
                regionNameList.add(brandAgentItemSaveRequest.getProvince());
            }
            if (StrUtil.isNotBlank(brandAgentItemSaveRequest.getCity())) {
                regionNameList.add(brandAgentItemSaveRequest.getCity());
            }
            if (StrUtil.isNotBlank(brandAgentItemSaveRequest.getDistrict())) {
                regionNameList.add(brandAgentItemSaveRequest.getDistrict());
            }
            if (StrUtil.isNotBlank(brandAgentItemSaveRequest.getStreet())) {
                regionNameList.add(brandAgentItemSaveRequest.getStreet());
            }
            if (StrUtil.isNotBlank(tribe)) {
                regionNameList.add(tribe);
            }
            if (StrUtil.isNotBlank(community)) {
                regionNameList.add(community);
            }
            String join = CollUtil.join(regionNameList, "/");
            list.add(join);
        }
        return list;
    }
}

